package org.biogroovy.io;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;

import org.biogroovy.io.ISeqWriter.NamingStrategy;
import org.biogroovy.models.AbsSequence;

/**
 * This class provides simple extension point for writing sequence model objects. 
 *
 */
public abstract class AbsSeqWriter<P extends AbsSequence> extends AbsWriter<P> implements ISeqWriter<P>{

	/**
	 * Constructor.
	 * @param defExtension The default file extension (i.e. ".gene.xml").
	 */
	public AbsSeqWriter(String defExtension) {
		super(defExtension);
	}
	
	@Override
	public void writeCollectionSeparately(Collection<P> seqs, Path outputDir,
			boolean autoCreateDir,
			NamingStrategy strategy)
			throws IOException {
		
		if(!outputDir.toFile().exists()){
			if (autoCreateDir){
				outputDir.toFile().mkdirs();
			}else {
				throw new IOException("The directory does not exist: " + outputDir);
			}
		}
		
		seqs.each {P seq ->
			String name = getName(seq, strategy);
			
			Path path = Paths.get(outputDir.toAbsolutePath(), name);
			
			write(seq, Files.newOutputStream(path));
			
		}
		
		
	}

	/**
	 * Gets the name of the sequence using the specified strategy.
	 * @param seq the sequence model object
	 * @param strategy the naming strategy to be used for the output file.
	 * @return the file name (without the extension).
	 */
	protected String getName(P seq, NamingStrategy strategy){
		String name = null;
		
		if (strategy == NamingStrategy.USE_ACCESSION){
			name = seq.getAccession();
		}else {
			name = seq.getSymbol();
		}
		
		return name + defExtension;
	}

}
